import axios from "axios"
import store from '../store'
import { BASE } from '@/conf.js'
import {  } from 'vant'
import { ElLoading, ElMessage } from "element-plus"
import router from "../router"
import { encode } from "js-base64"

const service = axios.create({
  baseURL: BASE.baseUrl,
  timeout: 30000 ,
  withCredentials: false,
})

let LoadingMessage

const MessageError = e => {
  LoadingMessage.close()
  ElMessage.error(e)
}

service.interceptors.request.use(
  request => {
    const { data } = request
    if(!(data instanceof FormData)){
      const { token } = store.getters
      request.headers['token'] = JSON.stringify(token)
      request.headers['citysn'] = encode(JSON.stringify(window.returnCitySN || ''))
      // request.data = Object.assign({},data,token)
    }
    LoadingMessage = ElLoading.service({
      lock: true,
      text: 'Loading',
      background: 'rgba(0, 0, 0, 0.7)',
    })
    return request
  },
  err=>{
    MessageError('无法发送请求')
    return Promise.reject(err.data)
  }
)


//拦截返回值
service.interceptors.response.use(
  response=> {
    const { data:{code,data,msg} } = response
    if(code !== 200){
      (code == 403) && router.push({name:'login'})
      MessageError(msg || '服务器异常')
      return Promise.reject(msg || data)
    }
    LoadingMessage.close()
    return Promise.resolve(data)
  },
  err=>{
    if(!err.request)
      MessageError('请求异常')
    else{
      const { status:code } = err.request
      if(code == 404)
        MessageError('未知的请求')
      else
        MessageError('请求服务器异常')
    }
    return Promise.reject(err)
  }
)
export default service